package com.mimo.push.service.impl;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.StringValue;
import com.mimo.common.comet.dto.ZoneDTO;
import com.mimo.common.exception.ApplicationException;
import com.mimo.common.rpc.proto.BaseResponseProto.BaseResponse;
import com.mimo.push.config.LogicSessionPoolFactory;
import com.mimo.push.service.IUserZoneService;

@Service
public class UserZoneServiceImpl implements IUserZoneService {

  @Autowired
  private LogicSessionPoolFactory logicSessionPoolFactory;

  @Override
  @Cacheable(cacheNames = "push:user:zone")
  public ZoneDTO getZoneByUser(String user) {
    Optional<ZoneDTO> opt = Optional.empty();
    BaseResponse resp = logicSessionPoolFactory.getLogicSessionStub().getZoneByUserId(StringValue.of(user));
    if (resp.hasSingularValue()) {
      try {
        opt = Optional.of(ZoneDTO
            .convert(resp.getSingularValue().getItem().unpack(com.mimo.common.rpc.proto.UserProto.ZoneDTO.class)));
      } catch (InvalidProtocolBufferException e) {
        throw new ApplicationException(e);
      }
    }
    return opt.orElse(null);
  }

  @Override
  @CacheEvict(cacheNames = "push:user:zone")
  public void clear(String user) {
    // 单纯的清空对应用户的Zone信息,以便于缓存重新加载
  }

}
